package nix.dom4j.stu.service;

import java.io.FileOutputStream;
import java.util.List;

import nix.dom4j.stu.vo.Student;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class StudentService {

	/**
	 * 添加学生
	 * @param student
	 * @throws Exception
	 */
	public static void addStu(Student student) throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read("src/nix/dom4j/stu/test/students.xml");
		Element root = document.getRootElement();
		Element stu = root.addElement("student");
		
		Element id = stu.addElement("id");
		Element name = stu.addElement("name");
		Element age = stu.addElement("age");
		
		id.setText(student.getId());
		name.setText(student.getName());
		age.setText(student.getAge());
		
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(new FileOutputStream("src/nix/dom4j/stu/test/students.xml"), format);
		writer.write(document);
		writer.close();
	}
	
	/**
	 * 删除学生
	 * 
	 * @param id
	 * @throws Exception
	 */
	public static void delStu(String id) throws Exception {
		SAXReader reader = new SAXReader();
		Document document = reader.read("src/nix/dom4j/stu/test/students.xml");
		List<Node> list = document.selectNodes("//id");
		for (Node node : list) {
			if (id.equals(node.getText())) {
				Element stu = node.getParent();
				Element stus = stu.getParent();
				stus.remove(stu);
			}
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		XMLWriter writer = new XMLWriter(new FileOutputStream("src/nix/dom4j/stu/test/students.xml"), format);
		writer.write(document);
		writer.close();
	}
	
	/**
	 * 查询学生
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	public static Student getStu(String id) throws Exception {
		Student student = null;
		SAXReader reader = new SAXReader();
		Document document = reader.read("src/nix/dom4j/stu/test/students.xml");
		List<Node> list = document.selectNodes("//id");
		for (Node node : list) {
			if (id.equals(node.getText())) {
				Element stu = node.getParent();
				student = new Student();
				student.setId(stu.element("id").getText());
				student.setName(stu.element("name").getText());
				student.setAge(stu.element("age").getText());
			}
		}
		return student;
	}
}
